<template>
  <div class="teacher-course-detail">
    <el-page-header @back="goBack" title="返回课程列表">
      <template #content>
        <h1>{{ courseInfo.couName || '章节管理' }}</h1>

      </template>

    </el-page-header>

    <template v-if="!error">
      <!-- 正常课程内容 -->
      <el-card class="course-info-card" v-loading="loading">
        <div class="course-header">
          <div class="course-cover">
            <img :src="defaultCover" alt="课程封面">
          </div>

          <div class="course-meta">
            <p class="intro">{{ courseInfo.couIntroduction || '暂无课程简介' }}</p>

            <div class="stats">
              <div class="stat-item">
                <span class="stat-label">价格:</span>

                <span class="stat-value">¥{{ formatPrice(courseInfo.couPrice) }}</span>

              </div>

              <div class="stat-item">
                <span class="stat-label">章节数:</span>

                <span class="stat-value">{{ chapters.length }}</span>

              </div>

              <div class="stat-item">
                <span class="stat-label">状态:</span>

                <el-tag :type="courseInfo.status === 1 ? 'success' : 'info'">
                  {{ statusText }}
                </el-tag>
              </div>

              <div class="stat-item">
                <span class="stat-label">浏览:</span>

                <span class="stat-value">{{ courseInfo.clicks || 0 }}</span>

              </div>

              <div class="stat-item">
                <span class="stat-label">收藏:</span>

                <span class="stat-value">{{ courseInfo.collectionCount || 0 }}</span>

              </div>

            </div>

          </div>

        </div>

      </el-card>

      <el-card class="chapters-card">
        <template #header>
          <div class="card-header">
            <h2>课程章节管理</h2>

            <el-button type="primary" size="small" @click="addChapter">
              <el-icon><Plus /></el-icon>添加章节
            </el-button>
          </div>

        </template>


        <div class="chapter-list">
          <draggable 
            v-model="chapters" 
            handle=".drag-handle"
            @end="onDragEnd"
            item-key="id"
            v-if="chapters.length > 0"
          >
            <template #item="{element, index}">
              <div class="chapter-item">
                <div class="chapter-content">
                  <el-icon class="drag-handle"><Rank /></el-icon>
                  <span class="index">第{{ index + 1 }}章</span>

                  <div class="info">
                    <h3>{{ element.title }}</h3>

                    <p class="chapter-intro" v-if="element.introduction">{{ element.introduction }}</p>

                    <p v-if="element.url" class="video-url">
                      <el-icon><VideoPlay /></el-icon>
                      <a @click="playVideo(element)">播放视频</a>

                    </p>

                  </div>

                </div>

                <div class="chapter-actions">
                  <el-tooltip content="上移" placement="top">
                    <el-button size="small" @click="moveUp(index)" :disabled="index === 0">
                      <el-icon><Top /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="下移" placement="top">
                    <el-button size="small" @click="moveDown(index)" :disabled="index === chapters.length - 1">
                      <el-icon><Bottom /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="编辑" placement="top">
                    <el-button size="small" @click="editChapter(index)">
                      <el-icon><Edit /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button size="small" type="danger" @click="removeChapter(index)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>

              </div>

            </template>

          </draggable>

          
          <el-empty v-else description="暂无章节内容" />
        </div>


        <div class="save-actions" v-if="orderChanged">
          <el-button type="primary" @click="saveChapterOrder" :loading="savingOrder">
            保存章节顺序
          </el-button>
          <el-button @click="resetChapterOrder">取消</el-button>
        </div>

      </el-card>

      <!-- 章节编辑对话框 -->
      <el-dialog 
        v-model="chapterDialogVisible" 
        :title="isEditingChapter ? '编辑章节' : '添加章节'" 
        width="50%"
        :close-on-click-modal="false"
      >
        <el-form :model="chapterForm" label-width="100px" ref="chapterFormRef">
          <el-form-item 
            label="章节标题" 
            prop="title" 
            :rules="[{ required: true, message: '请输入章节标题', trigger: 'blur' }]"
          >
            <el-input v-model="chapterForm.title" placeholder="请输入章节标题" clearable />
          </el-form-item>
          <el-form-item label="视频链接" prop="url">
            <el-input v-model="chapterForm.url" placeholder="请输入视频URL" clearable>
              <template #append>
                <el-button @click="selectVideo">选择视频</el-button>
              </template>

            </el-input>
          </el-form-item>
          <el-form-item label="章节简介" prop="introduction">
            <el-input 
              v-model="chapterForm.introduction" 
              type="textarea" 
              :rows="3" 
              placeholder="请输入章节简介" 
              maxlength="200" 
              show-word-limit 
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="chapterDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmChapter">确定</el-button>
        </template>

      </el-dialog>
    </template>


    <!-- 错误状态显示 -->
    <template v-else>
      <el-card class="error-card">
        <el-empty description="课程加载失败" :image="errorImage">
          <el-button type="primary" @click="retryLoad">重新加载</el-button>
        </el-empty>
      </el-card>
    </template>

  </div>

</template>


<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Rank, VideoPlay, Plus, Top, Bottom, Edit, Delete 
} from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import { courseApi } from '@/api/course'

const route = useRoute()
const router = useRouter()

// 状态管理
const loading = ref(false)
const savingOrder = ref(false)
const error = ref(false)
import defaultCover from '@/assets/fault.png'
// const defaultCover = ref('@/assets/fault.png')
// const errorImage = ref('@/assets/fault.png')

const courseInfo = ref({
  id: route.params.id,
  couName: '',
  couIntroduction: '',
  couPrice: 0,
  status: 0,
  clicks: 0,
  collectionCount: 0
})

const chapters = ref([])
const orderChanged = ref(false)
const originalOrder = ref([])

// 章节表单相关
const chapterDialogVisible = ref(false)
const isEditingChapter = ref(false)
const editingChapterIndex = ref(-1)
const chapterFormRef = ref(null)
const chapterForm = reactive({
  title: '',
  url: '',
  introduction: ''
})

// 计算属性
const statusText = computed(() => courseInfo.value.status === 1 ? '已发布' : '未发布')

// 方法
const formatPrice = (price) => price === 0 ? '免费' : Number(price).toFixed(2)

const loadCourseDetail = async () => {
  try {
    error.value = false
    loading.value = true
    
    const [courseRes, chaptersRes] = await Promise.all([
      courseApi.getCourseDetail(courseInfo.value.id),
      courseApi.getChapterTree(courseInfo.value.id)
    ])
    
    // 处理课程信息 - 不再获取封面图片
    const courseData = courseRes.data || {}
    courseInfo.value = {
      ...courseInfo.value,
      ...courseData
    }
    
    // 处理章节信息
    chapters.value = chaptersRes.data || []
    originalOrder.value = [...chapters.value]
    
  } catch (err) {
    console.error('获取课程详情失败:', err)
    error.value = true
    ElMessage.error('获取课程详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const retryLoad = () => {
  loadCourseDetail()
}

const playVideo = (chapter) => {
  if (!chapter.url) {
    ElMessage.warning('该章节没有视频内容')
    return
  }
  
  router.push({
    path: '/video-player',
    query: {
      courseId: courseInfo.value.id,
      chapterId: chapter.id
    }
  })
}

const addChapter = () => {
  Object.assign(chapterForm, { 
    title: '', 
    url: '', 
    introduction: '' 
  })
  isEditingChapter.value = false
  chapterDialogVisible.value = true
}

const editChapter = (index) => {
  const chapter = chapters.value[index]
  Object.assign(chapterForm, {
    title: chapter.title,
    url: chapter.url || '',
    introduction: chapter.introduction || ''
  })
  isEditingChapter.value = true
  editingChapterIndex.value = index
  chapterDialogVisible.value = true
}

const confirmChapter = async () => {
  try {
    await chapterFormRef.value.validate()
    
    const chapterData = {
      title: chapterForm.title.trim(),
      url: chapterForm.url?.trim() || null,
      introduction: chapterForm.introduction?.trim() || null,
      courseId: Number(courseInfo.value.id)
    }
    
    if (isEditingChapter.value) {
      const chapterId = chapters.value[editingChapterIndex.value].id
      await courseApi.updateChapter(chapterId, chapterData)
      Object.assign(chapters.value[editingChapterIndex.value], chapterData)
      ElMessage.success('章节更新成功')
    } else {
      const response = await courseApi.createChapter(chapterData)
      chapters.value.push(response.data)
      orderChanged.value = true
      ElMessage.success('章节添加成功')
    }
    
    chapterDialogVisible.value = false
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error(error.message || '操作失败')
    }
  }
}

const removeChapter = async (index) => {
  try {
    await ElMessageBox.confirm('确定要删除此章节吗?', '提示', { 
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    
    const chapterId = chapters.value[index].id
    await courseApi.deleteChapter(chapterId)
    chapters.value.splice(index, 1)
    orderChanged.value = true
    ElMessage.success('章节删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const saveChapterOrder = async () => {
  try {
    savingOrder.value = true
    await courseApi.updateChapterOrder({
      courseId: courseInfo.value.id,
      chapterIds: chapters.value.map(c => c.id)
    })
    originalOrder.value = [...chapters.value]
    orderChanged.value = false
    ElMessage.success('章节顺序已保存')
  } catch (error) {
    console.error('保存章节顺序失败:', error)
    ElMessage.error('保存失败: ' + error.message)
  } finally {
    savingOrder.value = false
  }
}

const resetChapterOrder = () => {
  chapters.value = [...originalOrder.value]
  orderChanged.value = false
}

const moveUp = (index) => {
  if (index > 0) {
    [chapters.value[index], chapters.value[index-1]] = [chapters.value[index-1], chapters.value[index]]
    orderChanged.value = true
  }
}

const moveDown = (index) => {
  if (index < chapters.value.length - 1) {
    [chapters.value[index], chapters.value[index+1]] = [chapters.value[index+1], chapters.value[index]]
    orderChanged.value = true
  }
}

const onDragEnd = () => {
  orderChanged.value = true
}

const selectVideo = () => {
  ElMessage.info('视频选择功能待实现')
}

const goBack = () => {
  router.back()
}

onMounted(() => {
  loadCourseDetail()
})
</script>


<style scoped>
.teacher-course-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.el-page-header {
  margin-bottom: 24px;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.el-page-header :deep(.el-page-header__content) h1 {
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.course-info-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: none;
}

.error-card {
  margin-top: 20px;
  text-align: center;
  padding: 40px 0;
}

.course-header {
  display: flex;
  gap: 24px;
  padding: 20px;
}

.course-cover {
  width: 280px;
  height: 158px;
  flex-shrink: 0;
  border-radius: 8px;
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.course-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.course-cover:hover img {
  transform: scale(1.02);
}

.course-meta {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.intro {
  color: #606266;
  margin: 0 0 16px;
  line-height: 1.6;
  font-size: 14px;
}

.stats {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  background-color: #f0f2f5;
  padding: 6px 12px;
  border-radius: 16px;
}

.stat-label {
  color: #606266;
  font-size: 13px;
}

.stat-value {
  color: #303133;
  font-weight: 500;
}

.chapters-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4px;
}

.card-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.chapter-list {
  margin-top: 12px;
}

.chapter-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  border: 1px solid #ebeef5;
}

.chapter-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
  border-color: #dcdfe6;
}

.chapter-content {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-grow: 1;
}

.drag-handle {
  cursor: move;
  color: #909399;
  font-size: 18px;
}

.index {
  color: #606266;
  min-width: 50px;
  font-weight: 500;
}

.info h3 {
  margin: 0;
  font-weight: 500;
  color: #303133;
  font-size: 15px;
}

.chapter-intro {
  color: #606266;
  font-size: 13px;
  margin: 6px 0 0;
  line-height: 1.5;
}

.video-url {
  margin: 6px 0 0;
  display: flex;
  align-items: center;
  gap: 4px;
  color: #409eff;
  font-size: 13px;
}

.video-url a {
  text-decoration: none;
  color: inherit;
  cursor: pointer;
}

.video-url a:hover {
  text-decoration: underline;
}

.chapter-actions {
  flex-shrink: 0;
  display: flex;
  gap: 8px;
}

.save-actions {
  margin-top: 20px;
  text-align: center;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .course-header {
    flex-direction: column;
  }
  
  .course-cover {
    width: 100%;
    height: auto;
    aspect-ratio: 16/9;
  }
  
  .stats {
    flex-direction: column;
    gap: 8px;
  }
  
  .chapter-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .chapter-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>